package com.first.xiinn.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.net.URLCodec;

import com.first.core.service.impl.BaseServiceImpl;
import com.first.core.util.EmallStringUtil;
import com.first.core.util.MailEngine;
import com.first.core.util.PagingBean;
import com.first.xiinn.dao.UserDao;
import com.first.xiinn.model.User;
import com.first.xiinn.service.UserService;

public class UserServiceImpl extends BaseServiceImpl<User> implements UserService{
	
	
	private UserDao userDao;
	private MailEngine mailEngine;

	public UserServiceImpl(UserDao dao, MailEngine mailEngine) {
		super(dao);
		this.userDao=dao;
		this.mailEngine = mailEngine;
	}

	public User getUser(String key) {
		return userDao.getUser(key);
	}
	
	/*
	 * (non-Javadoc)
	 * @see com.first.xiinn.service.BookService#searchAutor(java.lang.String)
	 */
	public List searchAutor(String userName) {
		List list = userDao.searchAutor(userName);
		return list;
	}
	public List getforgotten(String name,String email){
		return userDao.getforgotten(name, email);
	}
	/*
	 * (non-Javadoc)
	 * @see com.first.xiinn.service.UserService#get(java.lang.String)
	 */
	public User getById(String id) {
		return this.userDao.getById(id);
	}
	public User getregister(User u){
		return this.userDao.getregister(u);
	}
	
	public List<User> list() {
		return this.userDao.list();
	}
	
	public List<User> list(PagingBean pb){
		return this.userDao.list(pb);
	}
	
	@Override
	public List loginSearch(String login_id, String password) {
		return this.userDao.loginSearch(login_id, password);
	}

	@Override
	public User ibGetUserByEmail(String email) {
		return this.userDao.ibGetUserByEmail(email);
	}
	

	@Override
	public User ibGetUserByVerifyData(String verifyData) {
		return this.userDao.ibGetUserByVerifyData(verifyData);
	}

	@Override
	public User registerUser(User user, String url) {
		
		//生成随机码
		String randomPassword = new Date().getTime() + EmallStringUtil.randomString(8);
		byte[] userNameOld = new URLCodec().encode((user.getId() + "+" + randomPassword).getBytes());
        userNameOld = Base64.encodeBase64(userNameOld);
        String confirmUrl = new String(userNameOld);
		
        //保存用户信息
        user.setVerifyData(randomPassword);//设置邮箱验证随机码
		ibSave(user);
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("user", user);
        map.put("url", url + "/u/verifyInfo.do?data=" + confirmUrl);
        try{
			//发送激活邮件
			mailEngine.sendMessage(user.getEmail(), 
					"习嬴网注册邮箱激活", 
					"email-template/user_register_mail.vm", 
					map);
        }catch (Exception e) {
			logger.error(e.getMessage());
		}
		return null;
	}
	
}
